package com.zzl.study.auth.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.Map;

/**
 * @author: zhangzl
 * @date: 2024/6/6 16:25
 * @version: 1.0
 * @description: JSON工具类
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JacksonUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.registerModule(new JavaTimeModule());
    }

    /**
     * 对象转JSON字符串
     *
     * @param object 待转换的对象
     * @return JSON字符串
     */
    public static String toJson(Object object) {
        if (object == null) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * JSON字符串转对象
     *
     * @param json  JSON字符串
     * @param clazz 目标对象类型
     * @return 对象
     */
    public static <T> T toObject(String json, Class<T> clazz) {
        if (json == null) {
            return null;
        }
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * JSON字符串转对象
     *
     * @param json          JSON字符串
     * @param typeReference 目标对象类型
     * @return 对象
     */
    public static <T> T toObject(String json, TypeReference<T> typeReference) {
        if (json == null) {
            return null;
        }
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对象转Map
     *
     * @param object 待转换的对象
     * @return Map
     */
    public static Map<String, Object> toMap(Object object) {
        if (object == null) {
            return null;
        }
        return objectMapper.convertValue(object, new TypeReference<Map<String, Object>>() {
        });
    }

    /**
     * Map转对象
     *
     * @param map Map
     * @return 对象
     */
    public static <T> T toObject(Map<String, Object> map, Class<T> clazz) {
        if (map == null) {
            return null;
        }
        return objectMapper.convertValue(map, clazz);
    }

    /**
     * 获取ObjectMapper
     *
     * @return objectMapper 对象
     */
    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }

}
